package jitb.util;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.swing.Timer;

import jitb.lang.Array;
import jitb.lang.closure.Function;

public class TimerUtil {
	
	private static final class TimerItem {
		public final int index;
		public final Function<Object> callback;
		public final int delay;
		public final boolean callOnce;
		public final java.lang.Object[] arguments;
		
		public Timer timer;

		public TimerItem(final int index, final Function<Object> callback, final int delay, final boolean callOnce, final java.lang.Object[] arguments) {
			this.index = index;
			this.callback = callback;
			this.delay = delay;
			this.callOnce = callOnce;
			this.arguments = arguments;
		}
	}
	
	private static class TimerListener implements ActionListener {
		public final TimerItem item;
		
		public TimerListener(final TimerItem item) {
			this.item = item;
		}
		
		public void actionPerformed(ActionEvent evt) {
			item.callback.callVoid(null, item.arguments);
			if(item.callOnce) {
				TimerUtil.remove(item.index);
			}
		}
	}
	
	private static int _index = 0;
	private static List<TimerItem> _list = new ArrayList<TimerItem>();
	
	public static int createTimeout(final Function<Object> callback, final int delay, final java.lang.Object[] arguments) {
		return create(callback, delay, true, arguments);
	}
	
	public static int createInterval(final Function<Object> callback, int delay, final java.lang.Object[] arguments) {
		return create(callback, delay, false, arguments);
	}
	
	public static void removeTimeout(final int index) {
		remove(index);
	}
	
	public static void removeInterval(final int index) {
		remove(index);
	}
	
	private static int create(final Function<Object> callback, final int delay, final boolean callOnce, final java.lang.Object[] arguments) {
		_index++;
		
		TimerItem item = new TimerItem(_index, callback, delay, callOnce, arguments);
		Timer timer = new Timer(item.delay, new TimerListener(item));
		
		item.timer = timer;
		
		timer.start();
		
		return item.index;
	}
	
	private static void remove(final int index) {
		Iterator<TimerItem> iterator = _list.iterator();
		while(iterator.hasNext())
		{
			TimerItem item = iterator.next();
			if(item.index == index) {
				if(null != item.timer) {
					item.timer.stop();
				}
				
				iterator.remove();
				break;
			}
		}
	}
}
